# -*- coding:utf-8 -*-

import os
import datetime
from flask import render_template, redirect, url_for, flash, session, request, Response
from werkzeug.security import generate_password_hash
import uuid
from functools import wraps
from werkzeug.utils import secure_filename
import json

from . import home
from app.home.forms import RegisterForm, LoginForm, UserDetailForm, PwdForm, CommentForm
from app.models import User, UserLog, Preview, Tag, Movie, Comment, MovieCol
from app import db, app, rd


# 修改文件名称
def change_filename(filename):
    fileinfo = os.path.splitext(filename)
    filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(uuid.uuid4().hex) + fileinfo[-1]
    return filename


def user_login_required(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if 'user' not in session:
            return redirect(url_for('home.login', next=request.url))
        return func(*args, **kwargs)

    return decorated_function


@home.route("/login", methods=['GET', 'POST'])
def login():
    """登录"""
    form = LoginForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=data['name']).first()
        if not user.check_pwd(data['pwd']):
            flash('密码错误! ', 'error')
            return redirect(url_for('home.login'))
        session['user'] = user.name
        session['user_id'] = user.id
        user_log = UserLog(user_id=user.id, ip=request.remote_addr)
        db.session.add(user_log)
        db.session.commit()
        return redirect(url_for('home.user'))
    return render_template("/home/login.html", form=form)


@home.route("/logout", methods=['GET'])
@user_login_required
def logout():
    """登出"""
    session.pop('user', None)
    session.pop('user_id', None)
    return redirect(url_for('home.login'))


@home.route("/register", methods=['GET', 'POST'])
def register():
    """注册"""
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        user = User(name=data['name'], email=data['email'], phone=data['phone'],
                    pwd=generate_password_hash(data['pwd']), uuid=uuid.uuid4().hex)
        db.session.add(user)
        db.session.commit()
        flash('注册成功！ ', 'success')
    return render_template("/home/register.html", form=form)


@home.route("/user", methods=['GET', 'POST'])
@user_login_required
def user():
    """会员资料页面"""
    form = UserDetailForm()
    user = User.query.get(int(session["user_id"]))
    form.face.validators = []
    if request.method == "GET":
        form.name.data = user.name
        form.email.data = user.email
        form.phone.data = user.phone
        form.info.data = user.info
    if form.validate_on_submit():
        data = form.data
        file_face = secure_filename(form.face.data.filename)
        if not os.path.exists(app.config["FC_DIR"]):
            os.makedirs(app.config["FC_DIR"])
            os.chmod(app.config["FC_DIR"], 777)
        user.face = change_filename(file_face)
        form.face.data.save(app.config["FC_DIR"] + user.face)

        name_count = User.query.filter_by(name=data["name"]).count()
        if data["name"] != user.name and name_count == 1:
            flash("昵称已经存在！", "error")
            return redirect(url_for("home.user"))

        email_count = User.query.filter_by(email=data["email"]).count()
        if data["email"] != user.email and email_count == 1:
            flash("邮箱已经存在！", "error")
            return redirect(url_for("home.user"))

        phone_count = User.query.filter_by(phone=data["phone"]).count()
        if data["phone"] != user.phone and phone_count == 1:
            flash("手机号码已经存在！", "error")
            return redirect(url_for("home.user"))

        user.name = data["name"]
        user.email = data["email"]
        user.phone = data["phone"]
        user.info = data["info"]
        db.session.add(user)
        db.session.commit()
        flash("修改成功！", "success")
        return redirect(url_for("home.user"))
    return render_template("home/user.html", form=form, user=user)


@home.route("/pwd", methods=['GET', 'POST'])
@user_login_required
def pwd():
    """修改密码"""
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=session["user"]).first()
        if not user.check_pwd(data["old_pwd"]):
            flash("旧密码错误！", "error")
            return redirect(url_for('home.pwd'))
        user.pwd = generate_password_hash(data["new_pwd"])
        db.session.add(user)
        db.session.commit()
        flash("修改密码成功，请重新登录！", "success")
        return redirect(url_for('home.logout'))
    return render_template("home/pwd.html", form=form)


@home.route("/comments/<int:page>", methods=['GET'])
@user_login_required
def comments(page=None):
    """评论"""
    if page is None:
        page = 1
    page_data = Comment.query.join(User).filter(Comment.user_id == session['user_id']).order_by(
        Comment.addtime.desc()).paginate(page=page, per_page=3)
    return render_template("/home/comments.html", page_data=page_data)


@home.route("/loginlog/<int:page>", methods=['GET'])
@user_login_required
def loginlog(page=None):
    """登录日志"""
    if page is None:
        page = 1
    page_data = UserLog.query.filter_by(user_id=int(session["user_id"])).order_by(UserLog.addtime.desc()).paginate(
        page=page, per_page=3)
    return render_template("/home/loginlog.html", page_data=page_data)


@home.route("/moviecol", methods=['GET'])
@user_login_required
def moviecol():
    """电影收藏"""
    uid = request.args.get('uid', '')
    mid = request.args.get('mid', '')
    num = MovieCol.query.filter_by(user_id=int(uid), movie_id=int(mid)).count()
    if num == 1:
        data = dict(ok=1)
    if num == 0:
        moviecol = MovieCol(user_id=int(uid), movie_id=int(mid))
        db.session.add(moviecol)
        db.session.commit()
        data = dict(ok=0)
    return json.dumps(data)


@home.route("/moviecol/list/<int:page>", methods=['GET'])
@user_login_required
def moviecol_list(page=None):
    """电影收藏"""
    if page is None:
        page = 1
    page_data = MovieCol.query.join(Movie).join(User).filter(MovieCol.movie_id == Movie.id,
                                                             User.id == session['user_id']).order_by(
        MovieCol.addtime.desc()).paginate(page=page, per_page=3)
    return render_template('home/moviecol.html', page_data=page_data)


@home.route("/<int:page>")
def index(page=None):
    """首页"""
    if page is None:
        page = 1
    tags = Tag.query.all()
    page_data = Movie.query

    # 电影标签
    tid = request.args.get("tid", 0)
    if int(tid) != 0:
        page_data = page_data.filter_by(tag_id=int(tid))

    # 电影星级
    star = request.args.get("star", 0)
    if int(star) != 0:
        page_data = page_data.filter_by(tag_id=int(star))

    # 上映时间
    time = request.args.get("time", 0)
    if int(time) != 0:
        if int(time) == 1:
            page_data = page_data.order_by(Movie.addtime.desc())  # 升序
        else:
            page_data = page_data.order_by(Movie.addtime.asc())  # 降序

    # 播放数量
    pm = request.args.get("pm", 0)
    if int(pm) != 0:
        if int(pm) == 1:
            page_data = page_data.order_by(Movie.playnum.desc())  # 升序
        else:
            page_data = page_data.order_by(Movie.playnum.asc())  # 降序

    # 评论数量
    cm = request.args.get("cm", 0)
    if int(cm) != 0:
        if int(cm) == 1:
            page_data = page_data.order_by(Movie.commentnum.desc())  # 升序
        else:
            page_data = page_data.order_by(Movie.commentnum.asc())  # 降序
    page_data = page_data.paginate(page=page, per_page=3)

    p = dict(tid=tid, star=star, time=time, pm=pm, cm=cm)
    return render_template("/home/index.html", tags=tags, p=p, page_data=page_data)


@home.route("/animation")
def animation():
    """轮播"""
    data = Preview.query.all()

    return render_template("/home/animation.html", data=data)


@home.route("/search/<int:page>")
def search(page=None):
    """搜索页"""
    if page is None:
        page = 1
    key = request.args.get('key', '')
    count = Movie.query.filter(Movie.title.ilike('%' + key + '%')).count()
    page_data = Movie.query.filter(Movie.title.ilike('%' + key + '%')).paginate(page=page, per_page=3)
    return render_template("/home/search.html", key=key, page_data=page_data, count=count)


@home.route("/play/<int:id>/<int:page>", methods=['GET', 'POST'])
def play(id=None, page=None):
    """播放页"""
    movie = Movie.query.join(Tag).filter(Tag.id == Movie.tag_id, Movie.id == id).first_or_404()
    if page is None:
        page = 1
    page_data = Comment.query.join(Movie).filter(Comment.movie_id == movie.id).order_by(
        Comment.addtime.desc()).paginate(page=page, per_page=3)
    form = CommentForm()
    movie.playnum += 1
    if 'user' in session and form.validate_on_submit():
        data = form.data
        comment = Comment(content=data['content'], movie_id=movie.id, user_id=session['user_id'])
        db.session.add(comment)
        db.session.commit()
        movie.commentnum += 1
        db.session.add(movie)
        db.session.commit()
        flash('添加评论成功! ', 'success')
        return redirect(url_for('home.play', id=movie.id, page=1))
    db.session.add(movie)
    db.session.commit()
    return render_template("/home/play.html", movie=movie, form=form, page_data=page_data)


@home.route("/video/<int:id>/<int:page>", methods=['GET', 'POST'])
def video(id=None, page=None):
    """弹幕播放"""
    movie = Movie.query.join(Tag).filter(Tag.id == Movie.tag_id, Movie.id == id).first_or_404()
    if page is None:
        page = 1
    page_data = Comment.query.join(Movie).filter(Comment.movie_id == movie.id).order_by(
        Comment.addtime.desc()).paginate(page=page, per_page=3)
    form = CommentForm()
    movie.playnum += 1
    if 'user' in session and form.validate_on_submit():
        data = form.data
        comment = Comment(content=data['content'], movie_id=movie.id, user_id=session['user_id'])
        db.session.add(comment)
        db.session.commit()
        movie.commentnum += 1
        db.session.add(movie)
        db.session.commit()
        flash('添加评论成功! ', 'success')
        return redirect(url_for('home.video', id=movie.id, page=1))
    db.session.add(movie)
    db.session.commit()
    return render_template("/home/video.html", movie=movie, form=form, page_data=page_data)


@home.route("/tm/", methods=["GET", "POST"])
def tm():
    if request.method == "GET":
        # 获取弹幕消息队列
        id = request.args.get('id')
        key = "movie" + str(id)
        if rd.llen(key):
            msgs = rd.lrange(key, 0, 2999)
            res = {
                "code": 1,
                "danmaku": [json.loads(v) for v in msgs]
            }
        else:
            res = {
                "code": 1,
                "danmaku": []
            }
        resp = json.dumps(res)
    if request.method == "POST":
        # 添加弹幕
        data = json.loads(request.get_data().decode('utf-8'))
        msg = {
            "__v": 0,
            "author": data["author"],
            "time": data["time"],
            "text": data["text"],
            "color": data["color"],
            "type": data['type'],
            "ip": request.remote_addr,
            "_id": datetime.datetime.now().strftime("%Y%m%d%H%M%S") + uuid.uuid4().hex,
            "player": [
                data["player"]
            ]
        }
        res = {
            "code": 1,
            "data": msg
        }
        resp = json.dumps(res)
        rd.lpush("movie" + str(data["player"]), json.dumps(msg))
    return Response(resp, mimetype='application/json')
